package com.ineatconseil.yougo.pages.users.view;

import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.BeanEditForm;

import com.ineatconseil.yougo.beans.ActionType;
import com.ineatconseil.yougo.beans.User;
import com.ineatconseil.yougo.components.models.UserTypeSelectModel;
import com.ineatconseil.yougo.dto.UserDto;
import com.ineatconseil.yougo.exceptions.RestServiceException;
import com.ineatconseil.yougo.pages.AbstractPage;
import com.ineatconseil.yougo.pages.users.list.UsersList;
import com.ineatconseil.yougo.services.rest.RestPath;

public class UserView extends AbstractPage {

	@Property
	private User user;

	@Property
	@Persist(PersistenceConstants.SESSION)
	private long userId;

	@Component(id = "formUser")
	private BeanEditForm _form;

	@InjectPage
	private UsersList usersList;

	/**
	 * Load action.
	 */
	@Log
	void onActivate(long userId) {

		try {

			if (!isEmptyParameter(String.valueOf(userId))) {

				user =
						this.getMapper().map(
								this.getRestServiceInvoker().call(
										RestPath.getSimplePath(RestPath.PATH_USERS, String.valueOf(userId)),
										UserDto.class), User.class);
				this.userId = userId;
			} else {
				user = new User();
				this.userId = 0;
			}

		} catch (RestServiceException e) {
			_form.recordError(getRESTErrorMessage(e.getStatus()));
		}

	}

	/**
	 * Submit action.
	 */
	@Log
	Object onSuccess() {

		try {

			if (this.userId != 0) {

				// Update
				this.user.setId(this.userId);
				this.getRestServiceInvoker().update(
						RestPath.getSimplePath(RestPath.PATH_USERS, String.valueOf(userId)),
						getMapper().map(user, UserDto.class), UserDto.class);

				usersList.setActionMessageOk("user", ActionType.UPDATE);

			} else {

				// Create
				this.user.setId(null);
				this.getRestServiceInvoker().save(RestPath.getSimplePath(RestPath.PATH_USERS, ""),
						getMapper().map(user, UserDto.class), UserDto.class);

				usersList.setActionMessageOk("user", ActionType.CREATE);

			}

			return usersList;

		} catch (RestServiceException e) {
			_form.recordError(getRESTErrorMessage(e.getStatus()));
			return null;
		}

	}

	public SelectModel getUserTypesModel() {
		return (SelectModel) new UserTypeSelectModel(this.getRestServiceInvoker());
	}

}
